// 配置参数
const CONFIG = {
    itemsPerPage: 10,    // 每页显示数量
    autoRefresh: 30000   // 30秒自动刷新
};

let allMods = [];
let currentPage = 1;

// 初始化加载
document.addEventListener('DOMContentLoaded', () => {
    loadData();
    setupEventListeners();
    startAutoRefresh();
});

// 核心数据加载
async function loadData() {
    try {
        const response = await fetch('/static/data/modpacks.json');
        if (!response.ok) throw new Error('数据加载失败');
        const data = await response.json();
        
        allMods = data.modpacks.map(mod => ({
            ...mod,
            nameLower: mod.name_zh.toLowerCase(),
            dateTimestamp: new Date(mod.last_updated).getTime()
        }));
        
        renderMods();
    } catch (error) {
        console.error('数据加载错误:', error);
        alert('无法加载数据，请检查控制台');
    }
}

// 渲染逻辑
function renderMods() {
    const container = document.getElementById('mod-container');
    const searchTerm = document.getElementById('search').value.toLowerCase();
    const sortBy = document.getElementById('sort').value;

    // 过滤和排序
    let filtered = allMods.filter(mod => 
        mod.nameLower.includes(searchTerm)
    );

    switch(sortBy) {
        case 'downloads':
            filtered.sort((a, b) => b.downloads - a.downloads);
            break;
        case 'name':
            filtered.sort((a, b) => a.name_zh.localeCompare(b.name_zh));
            break;
        case 'date':
            filtered.sort((a, b) => b.dateTimestamp - a.dateTimestamp);
            break;
    }

    // 分页处理
    const start = (currentPage - 1) * CONFIG.itemsPerPage;
    const paginated = filtered.slice(start, start + CONFIG.itemsPerPage);
    
    container.innerHTML = paginated.map(mod => `
        <div class="mod-card">
            <h3 class="mod-title">${mod.name_zh}</h3>
            <p class="mod-detail">🕒 更新: ${mod.last_updated}</p>
            <p class="mod-detail">⬇️ 下载: ${mod.downloads.toLocaleString()}</p>
            <p class="mod-detail">🔗 <a href="${mod.url}" target="_blank">CurseForge页面</a></p>
        </div>
    `).join('');

    // 更新分页信息
    document.getElementById('page-info').textContent = 
        `第${currentPage}页 / 共${Math.ceil(filtered.length / CONFIG.itemsPerPage)}页`;
    document.getElementById('prev-page').disabled = currentPage === 1;
    document.getElementById('next-page').disabled = 
    currentPage >= Math.ceil(filtered.length / CONFIG.itemsPerPage);
}

// 事件监听
function setupEventListeners() {
    document.getElementById('search').addEventListener('input', () => {
        currentPage = 1;
        renderMods();
    });

    document.getElementById('sort').addEventListener('change', renderMods);
    
    document.getElementById('prev-page').addEventListener('click', () => {
        if (currentPage > 1) {
            currentPage--;
            renderMods();
        }
    });

    document.getElementById('next-page').addEventListener('click', () => {
        if (currentPage < Math.ceil(allMods.length / CONFIG.itemsPerPage)) {
            currentPage++;
            renderMods();
        }
    });
}

// 自动刷新
function startAutoRefresh() {
    setInterval(async () => {
        try {
            const response = await fetch('/static/data/modpacks.json?t=' + Date.now());
            if (!response.ok) throw new Error('刷新失败');
            const data = await response.json();
            allMods = data.modpacks;
            renderMods();
        } catch (error) {
            console.error('自动刷新失败:', error);
            // 可选：显示错误提示
        }
    }, CONFIG.autoRefresh);
}

